﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using Entities;

namespace ExpressionTest
{
    public static class ExpressionHelper
    {
        /// <summary>
        /// and连接
        /// </summary>
        public static Expression<Func<T, bool>> And<T>(this Expression<Func<T, bool>> lambda1, Expression<Func<T, bool>> lambda2) where T:BaseEntity
        {
            return MergExpression(lambda1, lambda2, ExpressionType.And);
        }

        /// <summary>
        /// Or连接
        /// </summary>
        public static Expression<Func<T, bool>> Or<T>(this Expression<Func<T, bool>> lambda1, Expression<Func<T, bool>> lambda2) where T:BaseEntity
        {
            return MergExpression(lambda1, lambda2, ExpressionType.Or);
        }

        /// <summary>
        /// 合并两个表达式
        /// </summary>
        public static Expression<Func<T, bool>> MergExpression<T>(this Expression<Func<T, bool>> lambda1, Expression<Func<T, bool>> lambda2, ExpressionType type) where T:BaseEntity
        {
            //创建参数表达式
            InvocationExpression invocation = Expression.Invoke(lambda1, lambda2.Parameters.Cast<Expression>());
            //创建and运算
            BinaryExpression binary = type == ExpressionType.And
                ? Expression.And(lambda2.Body, invocation)
                : Expression.Or(lambda2.Body, invocation);
            //生成lambda表达式
            var exp = Expression.Lambda<Func<T, bool>>(binary, lambda2.Parameters);
            return exp;
        }

        public enum ExpressionType
        {
            And=1,
            Or=2
        }
    }
}
